import 'package:flutter/foundation.dart';
import '../models/task_model.dart';
import '../services/task_service.dart';
import '../services/notification_service.dart';

/// 任务视图模型
/// 连接UI和数据服务，处理任务数据的业务逻辑
class TaskViewModel with ChangeNotifier {
  final TaskService _taskService;
  final NotificationService _notificationService;

  List<TaskModel> _ongoingTasks = [];
  List<TaskModel> _completedTasks = [];
  List<TaskModel> _notStartedTasks = [];
  bool _isLoading = false;

  TaskViewModel(this._taskService, this._notificationService) {
    // 初始化通知服务
    _notificationService.initialize();
  }

  List<TaskModel> get ongoingTasks => _ongoingTasks;
  List<TaskModel> get completedTasks => _completedTasks;
  List<TaskModel> get notStartedTasks => _notStartedTasks;
  bool get isLoading => _isLoading;

  /// 加载进行中的任务
  Future<void> loadOngoingTasks() async {
    _setLoading(true);
    _ongoingTasks = _taskService.getTasksByStatus('ongoing');
    _setLoading(false);
  }

  /// 加载已完成的任务
  Future<void> loadCompletedTasks() async {
    _setLoading(true);
    _completedTasks = _taskService.getTasksByStatus('completed');
    _setLoading(false);
  }

  /// 加载未开始的任务
  Future<void> loadNotStartedTasks() async {
    _setLoading(true);
    _notStartedTasks = _taskService.getTasksByStatus('notStarted');
    _setLoading(false);
  }

  /// 添加任务
  Future<void> addTask(TaskModel task) async {
    _setLoading(true);
    await _taskService.addTask(task);
    // 如果启用了提醒，安排通知
    if (task.reminderEnabled) {
      _notificationService.scheduleDailyReminder(task.id, task.name);
    }
    _setLoading(false);
  }

  /// 更新任务
  Future<void> updateTask(TaskModel task) async {
    _setLoading(true);
    await _taskService.updateTask(task);
    // 更新通知状态
    if (task.reminderEnabled) {
      _notificationService.scheduleDailyReminder(task.id, task.name);
    } else {
      _notificationService.cancelReminder(task.id);
    }
    _setLoading(false);
  }

  /// 删除任务
  Future<void> deleteTask(String taskId) async {
    _setLoading(true);
    await _taskService.deleteTask(taskId);
    _notificationService.cancelReminder(taskId);
    _setLoading(false);
  }

  /// 清空已完成任务
  Future<void> clearCompletedTasks() async {
    _setLoading(true);
    for (final task in _completedTasks) {
      await _taskService.deleteTask(task.id);
      _notificationService.cancelReminder(task.id);
    }
    _completedTasks = [];
    _setLoading(false);
  }

  /// 根据ID获取任务
  TaskModel? getTaskById(String id) {
    final allTasks = [..._ongoingTasks, ..._completedTasks, ..._notStartedTasks];
    return allTasks.firstWhere((task) => task.id == id, orElse: () => TaskModel.empty());
  }

  /// 打卡任务
  Future<void> toggleTaskCompletion(String taskId, DateTime date) async {
    _setLoading(true);
    final task = _taskService.getAllTasks().firstWhere(
      (t) => t.id == taskId,
      orElse: () => TaskModel.empty(),
    );
    if (task.id.isNotEmpty) {
      task.toggleTodayCompletion(date);
      await _taskService.updateTask(task);
      // 重新加载当前标签页的任务
      if (task.status == 'ongoing') {
        await loadOngoingTasks();
      } else if (task.status == 'completed') {
        await loadCompletedTasks();
      }
    }
    _setLoading(false);
  }

  /// 一键打卡
  Future<void> completeAllTodayTasks() async {
    _setLoading(true);
    final today = DateTime.now();
    for (final task in _ongoingTasks) {
      if (!task.isTodayCompleted(today)) {
        task.toggleTodayCompletion(today);
        await _taskService.updateTask(task);
      }
    }
    await loadOngoingTasks();
    _setLoading(false);
  }

  /// 标记所有今日任务为已完成（兼容旧调用）
  Future<void> markAllTodayAsCompleted() async {
    await completeAllTodayTasks();
  }

  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }
}